<?php

namespace app\api\controller\admin;

use app\common\controller\TApi;
use think\Db;

/**
 * 值班接口
 */
class Guard extends TApi
{
    protected $noNeedRight = ['*'];
    protected $weekArr = ['日','一','二','三','四','五','六'];

    //值班列表
    public function guardList() {
        $query = [];
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $search = $this->request->get('search');
        if($search) {
            $query = ['admin.nickname' => ['LIKE', '%'.$search.'%']];
        }

        $list = Db::name('dts_approve_guard')->alias('guard')
        ->field('guard.id,guard.guard_time,guard.guard_week,guard.status,guard.files,GROUP_CONCAT(DISTINCT admin.nickname) as admin__nickname')
        ->join('admin admin', 'FIND_IN_SET(admin.id,guard.admin_ids)', 'left')
        ->where($query)
        ->group('guard.id')
        ->order('guard.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //值班详情
    public function guardInfo() {
        $guardId = $this->request->get('id');

        $info = Db::name('dts_approve_guard')->alias('guard')
        ->field('guard.*,GROUP_CONCAT(DISTINCT admin.nickname) as admin__nickname')
        ->join('admin admin', 'FIND_IN_SET(admin.id,guard.admin_ids)', 'left')
        ->where(['guard.id' => $guardId])
        ->find();

        $this->success('success', $info);
    }

    //发起值班
    public function applyFGuard() {
        $admin_ids = $this->request->post('admin_ids');
        $admin_json = $this->request->post('admin_json');
        $guard_time = $this->request->post('guard_time');
        $guard_week = $this->request->post('guard_week');
        $guard_log = $this->request->post('guard_log');
        $status = $this->request->post('status', 0);
        $files = $this->request->post('files');
        $files_json = $this->request->post('files_json');

        if(!$admin_ids || !$guard_log) {
            $this->error('请提交值班数据');
        }

        if(!$guard_time || !$guard_week) {
            $guard_time = date('Y-m-d', time());
            $guard_week = '周' . $this->weekArr[date('w', time())];
        }

        $data = [
            'admin_ids' => $admin_ids,
            'admin_json' => $admin_json,
            'guard_time' => $guard_time,
            'guard_week' => $guard_week,
            'guard_log' => $guard_log,
            'status'    => $status,
            'files'     => $files,
        ];
        if($files_json) {
            $data['files_json'] = html_entity_decode($files_json);
        }

        \app\admin\model\dts\approve\Guard::create($data);

        $this->success('success');
    }
}